<?php

namespace App\Services;
use App\Enums\ParamsEnums;
use App\Models\Cms_Match;
use App\Models\Cms_Member;
use Illuminate\Support\Facades\DB;

class MemberService
{
    public function getMemberList($params)
    {
        return Cms_Member::getFilter($params)
            ->select(['id','username'])
            ->take(10)
            ->get();
    }


    public function getMemberCoudList($params)
    {
        // 手动列出 membercoud 表中需要的字段
        $memberCoudFields = config('fields.memberCoud');
        // 将字段转换为字符串格式，用于 SQL 查询
        $memberCoudFieldsString = implode(', ', $memberCoudFields);

        $result = DB::table('cms_member as m')
            ->join('cms_member_coud as mc', 'm.id', '=', 'mc.mid')
            ->select('m.id','m.sn','m.username','m.gender','m.avatar','m.created_at')
            ->addSelect(DB::raw($memberCoudFieldsString))
            ->where(function($query) use ($params) {
                if (isset($params['username']) && !empty($params['username'])) {
                    $query->where('m.username', 'like', '%' . $params['username'] . '%');
                }
            })
            ->where(function($query) use ($params) {
                if (isset($params['job']) && !empty($params['job'])) {
                    $query->where('mc.job', 'like', '%' . $params['job'] . '%');
                }
            })
            ->orderBy('created_at','desc')
            ->paginate($params['pageSize']);

        foreach ($result as &$row) {
            ParamsEnums::turnFormat($row);
        }
        $list['total'] = $result->total();
        $list['list'] = $result->items();
        return $list;
    }

    public function getMatchList($params)
    {
        $params['gender'] = $params['gender'] == 1 ? 2 : 1;

        $result = Cms_Member::getMatchConditions($params)
            ->select(['id','sn','username','avatar','created_at','state'])
            ->paginate($params['pageSize']);
        foreach ($result as &$row) {
            $isMatch = Cms_Match::where('mid', $params['mid'])
                ->where('otherid', $row->id)
                ->where('is_del',0)
                ->first();
            if (!empty($isMatch))
                $row->status = 1;   //已加入匹配列表
            else
                $row->status = 0;   //未加入匹配列表或已删除
        }
        $list['total'] = $result->total();
        $list['list'] = $result->items();
        return $list;
    }
}
